02 / 07

How can you update the state of a component in React?

The setState() method is used to update the state of a component in React. It can be used within class components to update the state with new data, which triggers a re-render of the component.

Difficulty: 5/10
Topics: useState hook, class setState, state immutability

Scenario Questions

0-2 years experience
  1. 1

    You need to toggle a boolean flag when a button is clicked in a functional component. How would you implement the state update?

  2. 2

    If you call setState (or setCount) twice in a row with the same value, what will the UI show and why?

2-5 years experience
  1. 1

    You added a new input field to a form component and used setState to store its value, but the input becomes unresponsive. Walk me through how you'd debug this.

  2. 2

    When updating an array in state by pushing a new item, the component doesn't re-render. Explain why and how you'd fix it.

5-8 years experience
  1. 1

    Our dashboard component receives a large list via props and filters it locally, storing the filtered list in state. Users report lag when typing in the filter box. How would you redesign the state updates to improve performance?

  2. 2

    We have a class component that uses setState in several lifecycle methods, causing an infinite render loop. How would you identify and resolve the issue, and what patterns would you adopt to avoid it in the future?

8+ years experience
  1. 1

    The team is migrating a legacy codebase from class components with setState to functional components with useState and useReducer. What strategy would you propose to manage state updates consistently across the app, and how would you handle edge cases like async state updates?

  2. 2

    We need to share mutable state across many unrelated components without prop drilling. Discuss the trade‑offs of using React Context versus a state‑management library, focusing on how state updates propagate and affect performance.

Follow-up Questions

  • Can you show how you'd use the functional updater form of setState or setState hook?
  • What does React do differently when batching state updates inside event handlers versus async callbacks?
  • Why is mutating state directly a problem for rendering?